package com.skp.shaphan.ui.util;

import java.awt.Window;
import java.io.IOException;
import java.net.URL;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;

import javax.swing.SwingUtilities;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

import com.skp.shaphan.ShaphanApp;

public class ShaphanJFXPanel extends JFXPanel implements AncestorListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Object controller;

	public ShaphanJFXPanel(final String fxmlPath, final Object controller) {
		super();
		
		this.controller = controller;
		addAncestorListener(this);
		
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
            	Parent root;
            	try {
					URL location = controller.getClass().getResource(fxmlPath);
					if(location == null) {
						throw new IOException("Could not load resource " + fxmlPath);
					}
					FXMLLoader fxmlloader = new FXMLLoader(location);
					fxmlloader.setController(controller);
					root = (Parent)fxmlloader.load();
					Scene scene = new Scene(root);
			        setScene(scene);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            //initFX(fxPanel);
            }
       });

	}
	
	public Object getController() {
		return controller;
	}

	@Override
	public void ancestorAdded(AncestorEvent e) {
		Window window = SwingUtilities.windowForComponent(e.getComponent());
		if(controller instanceof WindowAttachment) {
			System.out.println("Attaching window " + window.getName());
			((WindowAttachment)controller).attachWindow(window);
		}
	}

	@Override
	public void ancestorMoved(AncestorEvent e) {
	}

	@Override
	public void ancestorRemoved(AncestorEvent e) {
	}
	
	public interface WindowAttachment {
		public void attachWindow(Window window);
	}
}
